﻿using System.Text.RegularExpressions;
using System.Xml;

namespace Mohe.Scada.Util.S7Parser
{
    public class S7IOParser
    {
        /// <summary>
        /// 解析XML文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public List<DefinitionSection> ParseXML(string fileName)
        {
            List<DefinitionSection> lst = new List<DefinitionSection>();
            DefinitionSection inputSection = new DefinitionSection();
            DefinitionSection outputSection = new DefinitionSection();
            inputSection.Name = "I0";
            inputSection.Type = DefinitionType.Input;
            outputSection.Name = "Q0";
            outputSection.Type = DefinitionType.Output;
            lst.Add(inputSection);
            lst.Add(outputSection);
            inputSection.StructItems = new List<DefinitionSection>();
            outputSection.StructItems = new List<DefinitionSection>();
            try
            {

                var xml = new XmlDocument();
                xml.Load(fileName);
                var nodeList = xml.SelectNodes("//Tagtable/*");

                foreach (XmlNode node in nodeList)
                {
                    var item = new DefinitionSection();

                    item.DataType = node.Attributes["type"].Value;
                    string addr = node.Attributes["addr"].Value;
                    item.Name = addr;
                    item.Desc = node.InnerText;
                    var matches = new Regex(@"\d+").Matches(addr);
                    item.Offset = int.Parse(matches[0].Value) * 8;
                    if (matches.Count > 1)
                    {
                        item.Offset += int.Parse(matches[1].Value);
                    }
                    if (addr.StartsWith("%I"))
                    {
                        item.Type = DefinitionType.Input;
                        inputSection.StructItems.Add(item);

                    }
                    else if (addr.StartsWith("%Q"))
                    {
                        item.Type = DefinitionType.Output;
                        outputSection.StructItems.Add(item);
                    }


                }

            }
            catch
            {

            }

            return lst;
        }
    }
}
